<?php

/**
 * 文档控制器
 *
 * @author 煤老板 <meok23@sina.com>
 * @date   2017-06-07
 */

namespace app\admin\controller;

use app\admin\model\Chapter;
use app\admin\model\Doc;
use app\common\logic\Response;
use fw\base\Conf;
use fw\base\View;
use fw\db\DB;
use fw\tool\Json;
use fw\tool\Request;
use fw\tool\Session;

class ControllerDoc extends Base
{
    public function add()
    {
        if (Request::isPost()) {
            $_POST['manager_id'] = Session::gi()->get('auth.manager_id');
            $ret = Doc::gi()->add();

            echo Json::encode($ret);
        } else {
            View::render('doc_add');
        }
    }

    public function update()
    {
        if (Request::isPost()) {
            $_POST['manager_id'] = Session::gi()->get('auth.manager_id');
            $ret = Doc::gi()->update();
            $ret['code'] == 200 && $ret['code'] = 0;

            echo Json::encode($ret);
        } else {
            // 参数获取
            $doc_id = (int)Request::get('doc_id');

            // 参数校验
            if ($doc_id < 1) {
                View::error(['msg' => 'Require doc_id.']);
            }

            // 查询数据
            $data = Doc::gi()->getInfo(['doc_id' => $doc_id]);

            View::render('doc_update', ['data' => $data]);
        }
    }

    public function browse()
    {
        // 参数获取
        $length = Conf::$all['page_length'];
        $current_page = (int)Request::get('page', null, 1);

        // 条数总计
        $list_count = Doc::gi()->getList(['is_count' => true]);
        $page_total = ceil($list_count / $length);

        // 分页
        $option = [
            'current_page' => $current_page,
            'page_total'   => $page_total,
            'list_count'   => $list_count,
        ];
        $page = new \app\common\logic\Page($option);
        $page_show = $page->show();

        // 查询列表
        $data = Doc::gi()->getList(['length' => $length, 'page' => $current_page]);

        View::render('doc_browse', [
            'data'      => $data,
            'page_show' => $page_show,
        ]);
    }

    public function del()
    {
        // 文档标识验证
        $signs = Request::post('signs', 'trim');

        if (!empty($signs)) {
            $ret = DB::table('doc')->where('title=:signs', [':signs' => $signs])->count();
            $ret < 1 && $signs = null;
        }
        if (empty($signs)) {
            $resp = Response::to([20, 'Signs error.']);
            echo Json::encode($resp);
            return;
        }

        // 验证通过才允许下一步操作
        $option = [
            'doc_id'  => (int)Request::post('doc_id'),
            'op_user' => Session::gi()->get('auth.manager_id'),
        ];

        // 清空所有章节
        $ret = Chapter::gi()->truncate($option);

        // 删除文档
        if (in_array($ret['code'], [0, 404])) {
            $ret = Doc::gi()->del($option);
        }

        echo Json::encode($ret);
    }
}
